package com.example.guideme;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;


public class ViewMap extends MapActivity implements LocationListener {

	MapView map;
	ArrayList<OverlayItem> overlayItemArray;

	private LocationManager locManager;
	private String provider;
	private double latitude;
	private double longitude;
	public Geocoder geocoder;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_map);

		Intent intent = getIntent();
		String lat = intent.getStringExtra(LocationActivity.LAT);
		String lon = intent.getStringExtra(LocationActivity.LON);
		String add = intent.getStringExtra(LocationActivity.ADD);

		latitude = Double.parseDouble(lat);
		longitude = Double.parseDouble(lon);
		Toast.makeText(this, "Your location: " + add, Toast.LENGTH_LONG).show();

		map = (MapView)findViewById(R.id.mvMain);
		map.setSatellite(false);
		//map.setStreetView(false);
		map.getController().setCenter(getPoint(latitude, longitude));
		map.getController().setZoom(18);
		map.setBuiltInZoomControls(true);

		Drawable marker = getResources().getDrawable(R.drawable.ic_map_guideme);
		marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());
		map.getOverlays().add(new InterestingLocations(marker, latitude, longitude));

		locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		provider = locManager.getBestProvider(criteria, false);
		Location loc = locManager.getLastKnownLocation(provider);
		geocoder = new Geocoder(this,Locale.ENGLISH);

		if(loc == null)
		{
			Toast.makeText(this, "No Provider available: " + provider, Toast.LENGTH_LONG).show();
		} 
	}

	private GeoPoint getPoint(double lat, double lon) 
	{
		return(new GeoPoint((int)(lat*1000000.0), (int)(lon*1000000.0))); 
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_view_map, menu);
		return true;
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	class InterestingLocations extends ItemizedOverlay<OverlayItem>
	{

		private List<OverlayItem> locations = new ArrayList<OverlayItem>();
		private Drawable marker;

		public InterestingLocations(Drawable defaultMarker, double Latitude, double Longitude) 
		{
			super(defaultMarker);
			this.marker = defaultMarker;
			GeoPoint myPlace = new GeoPoint((int)(Latitude*1000000.0), (int)(Longitude*1000000.0));
			locations.add(new OverlayItem(myPlace , "My location", "My location"));
			populate();
		}

		@Override
		protected OverlayItem createItem(int i) 
		{
			// TODO Auto-generated method stub
			return locations.get(i);
		}

		@Override
		public int size() 
		{
			// TODO Auto-generated method stub
			return locations.size();
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) 
		{
			// TODO Auto-generated method stub
			super.draw(canvas, mapView, shadow);
			boundCenterBottom(marker);
		}
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		double rawLat = (double) (location.getLatitude());
		double rawLon = (double) (location.getLongitude());       
		latitude = clipValue(rawLat,7);
		longitude = clipValue(rawLon,7);  

		//map = (MapView)findViewById(R.id.mvMain);
		//map.setSatellite(false);
		//map.setStreetView(false);
		map.getController().setCenter(getPoint(latitude, longitude));
		map.getController().setZoom(18);
		map.setBuiltInZoomControls(true);

		Drawable marker = getResources().getDrawable(R.drawable.ic_map_guideme);
		marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());
		map.getOverlays().clear();
		map.getOverlays().add(new InterestingLocations(marker, latitude, longitude));
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "Disable Provider "+ provider, Toast.LENGTH_LONG).show();

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "Enabled Provider"+ provider, Toast.LENGTH_LONG).show();

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onResume(){
		super.onResume();
		locManager.requestLocationUpdates(provider, 400, 1, this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		locManager.removeUpdates(this);
	}

	public static double clipValue(double value, int places) 
	{
		if (places < 0) throw new IllegalArgumentException();
		long factor = (long) Math.pow(10, places);
		value = value * factor;
		long tmp = Math.round(value);
		return (double) tmp / factor;
	}

	public String getAddress(Double lat, Double lon)
	{
		List<Address> addresses = null;
		String addressText = "";

		try 
		{
			addresses = geocoder.getFromLocation(lat,lon,1);
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}

		if(addresses != null && addresses.size() > 0 )
		{
			Address address = addresses.get(0);
			addressText = String.format("%s, %s, %s, %s",
					address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
							address.getLocality(),
							address.getCountryName(),
							address.getPostalCode());
		}
		return addressText;	 
	}

	public void locateMe(View view)
	{
		String currentAddress = getAddress(latitude, longitude);
		Toast.makeText(this, "Your location: " + currentAddress, Toast.LENGTH_LONG).show();

		map.getController().setCenter(getPoint(latitude, longitude));
		map.getController().setZoom(18);
		map.setBuiltInZoomControls(true);

		Drawable marker = getResources().getDrawable(R.drawable.ic_map_guideme);
		marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());
		map.getOverlays().clear();
		map.getOverlays().add(new InterestingLocations(marker, latitude, longitude));
	}

	public void findPlaces(View view)
	{
		Intent intent = new Intent();
		intent.setComponent(new ComponentName("com.androidhive.googleplacesandmaps","com.androidhive.googleplacesandmaps.MainActivity"));
		startActivity(intent);	
	}

}
